<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="报警时间" prop="alarmTime">
        <el-date-picker
          v-model="queryParams.alarmTimeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          format="YYYY-MM-DD HH:mm:ss"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 300px"
        />
      </el-form-item>
      <el-form-item label="报警等级" prop="alarmLevel">
        <el-select
          v-model="queryParams.alarmLevel"
          style="width: 100px"
          clearable
          placeholder="请选择报警等级"
        >
          <el-option
            v-for="item in alarmLevelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="报警类型" prop="alarmType">
        <el-select
          v-model="queryParams.alarmType"
          clearable
          placeholder="请选择报警类型"
          style="width: 200px"
        >
          <el-option
            v-for="item in alarmTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="设备名称" prop="deviceName">
        <el-input
          v-model="queryParams.deviceName"
          placeholder="请输入设备名称"
          clearable
        />
      </el-form-item>
      <!-- <el-form-item label="报警状态" prop="status">
        <el-select
          v-model="queryParams.status"
          clearable
          placeholder="请选择报警状态"
          style="width: 150px"
        >
          <el-option label="未处理" value="0" />
          <el-option label="处理中" value="1" />
          <el-option label="已处理" value="2" />
          <el-option label="已忽略" value="3" />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="Download" @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Search" @click="toggleSearch">{{
          showSearch ? "隐藏搜索" : "显示搜索"
        }}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Refresh" @click="getList"
          >刷新</el-button
        >
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="tableData"
      style="min-height: 500px; height: 650px"
      @row-click="handleRowClick"
    >
      <el-table-column
        prop="alarmTime"
        align="center"
        label="报警时间"
        width="200"
        show-overflow-tooltip
      >
        <template #default="scope">
          {{ formatDate(scope.row.alarmTime) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="deviceName"
        align="center"
        label="设备名称"
        width="150"
        show-overflow-tooltip
      />
      <el-table-column
        prop="alarmLevel"
        align="center"
        label="报警等级"
        width="150"
      >
        <template #default="scope">
          <el-tag :type="getAlarmLevelTagType(scope.row.alarmLevel)">
            {{ getAlarmLevelName(scope.row.alarmLevel) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="alarmKind"
        align="center"
        label="报警类型"
        width="120"
      >
        <template #default="{ row }">
          {{ getAlarmKindName(row.alarmKind) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="alarmMessage"
        align="center"
        label="报警内容"
        min-width="200"
        show-overflow-tooltip
      />
      <el-table-column
        prop="status"
        align="center"
        label="处理状态"
        width="150"
      >
        <template #default="scope">
          <el-tag :type="getStatusTagType(scope.row.status)">
            {{ getStatusName(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="acknowledgedContent"
        align="center"
        label="处理内容"
        width="130"
        show-overflow-tooltip
      />
      <el-table-column
        prop="acknowledgedBy"
        align="center"
        label="处理人"
        width="100"
      />
      <el-table-column
        prop="acknowledgedTime"
        align="center"
        label="处理时间"
        width="160"
        show-overflow-tooltip
      >
        <template #default="scope">
          {{ formatDate(scope.row.acknowledgedTime) }}
        </template>
      </el-table-column>
      <el-table-column
        prop="remark"
        align="center"
        label="备注"
        min-width="150"
        show-overflow-tooltip
      />
      <el-table-column label="操作" align="center" width="180" fixed="right">
        <template #default="scope">
          <el-button
           v-if="scope.row.status === 0"
            type="primary"
            size="small"
            @click.stop="handleDispose(scope.row)"
            >处置</el-button
          >
          <el-button
            v-if="scope.row.status === 0"
            type="warning"
            size="small"
            @click.stop="handleIgnore(scope.row)"
            >忽略</el-button
          >
          <el-tag v-if="scope.row.status !== 0" type="success" size="small"
            >已处理</el-tag
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 报警详情对话框 -->
    <el-dialog
      title="报警详情"
      v-model="detailDialogVisible"
      width="60%"
      append-to-body
      destroy-on-close
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="报警时间">
          {{ formatDate(selectedRecord.alarmTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="设备名称">
          {{ selectedRecord.deviceName }}
        </el-descriptions-item>
        <el-descriptions-item label="报警等级">
          <el-tag :type="getAlarmLevelTagType(selectedRecord.alarmLevel)">
            {{ getAlarmLevelName(selectedRecord.alarmLevel) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="报警类型">
          {{ getAlarmKindName(selectedRecord.alarmKind) }}
        </el-descriptions-item>
        <el-descriptions-item label="处理状态">
          <el-tag :type="getStatusTagType(selectedRecord.status)">
            {{ getStatusName(selectedRecord.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="处理人">
          {{ selectedRecord.acknowledgedBy || "-" }}
        </el-descriptions-item>
        <el-descriptions-item label="处理时间">
          {{ formatDate(selectedRecord.acknowledgedTime) }}
        </el-descriptions-item>
        <el-descriptions-item label="设备位置">
          {{ selectedRecord.deviceLocation || "-" }}
        </el-descriptions-item>
        <el-descriptions-item label="报警内容" :span="2">
          {{ selectedRecord.alarmMessage }}
        </el-descriptions-item>
        <el-descriptions-item label="处理说明" :span="2">
          {{ selectedRecord.acknowledgedContent || "-" }}
        </el-descriptions-item>

      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 报警处置对话框 -->
    <el-dialog
      title="报警处置"
      v-model="disposeDialogVisible"
      width="50%"
      append-to-body
      destroy-on-close
    >
      <el-form
        ref="disposeFormRef"
        :model="disposeForm"
        :rules="disposeRules"
        label-width="100px"
      >
        <el-form-item label="报警时间">
          <span>{{ formatDate(currentDisposeRecord.alarmTime) }}</span>
        </el-form-item>
        <el-form-item label="设备名称">
          <span>{{ currentDisposeRecord.deviceName }}</span>
        </el-form-item>
        <el-form-item label="报警内容">
          <span>{{ currentDisposeRecord.alarmMessage }}</span>
        </el-form-item>
        <el-form-item label="处理内容" prop="acknowledgedContent">
          <el-input
            v-model="disposeForm.acknowledgedContent"
            type="textarea"
            :rows="4"
            placeholder="请输入处理内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitDispose">保存</el-button>
          <el-button @click="disposeDialogVisible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 分页 -->
    <el-pagination
      @current-change="currentChange"
      :current-page="pagination.curPage"
      :page-size="pagination.pageSize"
      layout="total, prev, pager, next"
      :total="pagination.total"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getAlarmRecordsList,
  getAlarmRecord,
  exportAlarmRecords,
  saveAlarmRecord,
  submitAlarmConfirm,
} from "@/api/alarm/alarmRecords";
import { getAlarmLevelList } from "@/api/alarm/alarmLevel";
import { ALARM_KIND_OPTIONS, getAlarmKindName } from "@/utils/alarmConstants";

// 防抖函数
function debounce(func, wait) {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
}

const { proxy } = getCurrentInstance();

// 响应式数据
const tableData = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const detailDialogVisible = ref(false);
const disposeDialogVisible = ref(false);
const selectedRecord = ref({});
const currentDisposeRecord = ref({});

// 查询参数
const queryParams = reactive({
  alarmTimeRange: [],
  alarmLevel: "",
  alarmType: "",
  deviceName: "",
  status: "",
});

// 分页参数
const pagination = reactive({
  curPage: 1,
  pageSize: 10,
  total: 0,
});

// 报警等级选项（从接口获取）
const alarmLevelOptions = ref([]);

// 报警类型选项（使用统一枚举）
const alarmTypeOptions = ref(ALARM_KIND_OPTIONS);

// 处置表单
const disposeForm = reactive({
  id: null,
  acknowledgedContent: "",
  status: 2, // 已处理
});

// 处置表单验证规则
const disposeRules = reactive({
  acknowledgedContent: [{ required: true, message: "处理内容不能为空", trigger: "blur" }],
});

const disposeFormRef = ref();

// 格式化日期
function formatDate(dateStr) {
  if (!dateStr) return "-";
  const date = new Date(dateStr);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
}

// 获取报警等级标签类型
function getAlarmLevelTagType(level) {
  const levelOption = alarmLevelOptions.value.find(
    (item) => item.value === level
  );
  if (levelOption) {
    // 根据等级名称判断标签类型
    const name = levelOption.label;
    if (name.includes("紧急") || name.includes("严重")) return "danger";
    if (name.includes("重要") || name.includes("警告")) return "warning";
    if (name.includes("一般") || name.includes("普通")) return "primary";
    if (name.includes("提示") || name.includes("信息")) return "info";
  }
  return "info";
}

// 获取报警等级名称
function getAlarmLevelName(level) {
  const levelOption = alarmLevelOptions.value.find(
    (item) => item.value === level
  );
  return levelOption ? levelOption.label : level;
}

// 获取状态标签类型
function getStatusTagType(status) {
  const typeMap = {
    0: "danger", // 未处理
    1: "success", // 已处理
    2: "success", // 已处理
    3: "info", // 已忽略
  };
  return typeMap[status] || "info";
}

// 获取状态名称
function getStatusName(status) {
  const nameMap = {
    0: "未处理",
    2: "已处理",
    3: "已忽略",
  };
  return nameMap[status] || status;
}

/** 查询列表 */
function getList() {
  loading.value = true;
  let params = { ...pagination, ...queryParams };

  // 处理时间范围参数
  if (queryParams.alarmTimeRange && queryParams.alarmTimeRange.length === 2) {
    params.startTime = queryParams.alarmTimeRange[0];
    params.endTime = queryParams.alarmTimeRange[1];
  }
  delete params.alarmTimeRange;

  getAlarmRecordsList(params)
    .then((response) => {
      tableData.value = response.data.list || [];
      pagination.total = response.data.totalCount || 0;
      loading.value = false;
    })
    .catch((error) => {
      console.error("获取报警记录列表失败:", error);
      loading.value = false;
      ElMessage.error("获取报警记录列表失败，请稍后重试");
    });
}

// 创建防抖版本的查询函数
const debouncedGetList = debounce(getList, 300);

/** 获取报警等级选项 */
function getAlarmLevelOptions() {
  getAlarmLevelList({ pageSize: 1000 }) // 获取所有等级
    .then((response) => {
      const levels = response.data.list || [];
      alarmLevelOptions.value = levels.map((level) => ({
        label: level.name,
        value: level.code || level.id.toString(),
      }));
    })
    .catch((error) => {
      console.error("获取报警等级选项失败:", error);
      // 如果接口失败，使用默认选项
      alarmLevelOptions.value = [
        { label: "紧急", value: "urgent" },
        { label: "重要", value: "important" },
        { label: "一般", value: "normal" },
        { label: "提示", value: "info" },
      ];
    });
}

/** 搜索按钮操作 */
function handleQuery() {
  pagination.curPage = 1;
  loading.value = true;
  debouncedGetList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParams.alarmTimeRange = [];
  queryParams.alarmLevel = "";
  queryParams.alarmType = "";
  queryParams.deviceName = "";
  queryParams.status = "";
  pagination.curPage = 1;
  loading.value = true;
  debouncedGetList();
}

/** 切换搜索显示/隐藏 */
function toggleSearch() {
  showSearch.value = !showSearch.value;
}

/** 行点击事件 */
function handleRowClick(row) {
  selectedRecord.value = row;
  detailDialogVisible.value = true;
}

/** 导出按钮操作 */
function handleExport() {
  let params = { ...queryParams };

  // 处理时间范围参数
  if (queryParams.alarmTimeRange && queryParams.alarmTimeRange.length === 2) {
    params.startTime = queryParams.alarmTimeRange[0];
    params.endTime = queryParams.alarmTimeRange[1];
  }
  delete params.alarmTimeRange;

  proxy.download(
    "intra/alarm/alarmrecords/toExport",
    params,
    `报警记录_${new Date().getTime()}.xlsx`
  );
}

/** 分页变化 */
function currentChange(e) {
  pagination.curPage = e;
  loading.value = true;
  debouncedGetList();
}

/** 处置按钮操作 */
function handleDispose(row) {
  currentDisposeRecord.value = row;
  disposeForm.id = row.id;
  disposeForm.acknowledgedContent = "";
  disposeForm.status = 2; // 已处理
  disposeDialogVisible.value = true;
}

/** 忽略按钮操作 */
function handleIgnore(row) {
  ElMessageBox.confirm(`确定要忽略报警"${row.alarmContent}"吗？`, "确认忽略", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    const data = {
      id: row.id,
      status: 3, // 已忽略
    };

    saveAlarmRecord(data)
      .then(() => {
        ElMessage.success("忽略成功");
        getList(); // 刷新列表
      })
      .catch((error) => {
        console.error("忽略报警失败:", error);
        ElMessage.error("忽略失败，请稍后重试");
      });
  });
}

/** 提交处置 */
function submitDispose() {
  disposeFormRef.value.validate((valid) => {
    if (valid) {
      const data = {
        id: disposeForm.id,
        status: disposeForm.status,
        acknowledgedContent: disposeForm.acknowledgedContent,
      };

      // 调用新的处置接口
      submitAlarmConfirm(data)
        .then(() => {
          ElMessage.success("处置成功");
          disposeDialogVisible.value = false;
          getList(); // 刷新列表
        })
        .catch((error) => {
          console.error("处置报警失败:", error);
          ElMessage.error("处置失败，请稍后重试");
        });
    }
  });
}

// 页面初始化
onMounted(() => {
  getAlarmLevelOptions(); // 先获取报警等级选项
  getList();
});
</script>

<style lang="scss" scoped>
@import "@/assets/styles/variables.module.scss";

.app-container {
  padding: 10px 20px;
  background: $base-menu-background;
  min-height: 100vh;
}

// 搜索表单样式
.el-form {
  background: #ffffff;
  padding: 10px 20px;
  border-radius: 8px;
  margin-bottom: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .el-button {
    border-radius: 6px;
    font-weight: 500;

    &.el-button--primary {
      background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
      border: none;
      color: #ffffff;

      &:hover {
        background: linear-gradient(135deg, #3bc4b3 0%, #2aa3b8 100%);
        color: #ffffff;
      }
    }

    &:not(.el-button--primary) {
      background: linear-gradient(135deg, #909399 0%, #73767a 100%);
      border: none;
      color: #ffffff;

      &:hover {
        background: linear-gradient(135deg, #82848a 0%, #6c6e72 100%);
        color: #ffffff;
      }
    }
  }
}

// 按钮组样式
.mb8 {
  margin-bottom: 10px;
  margin-left: 0 !important;
  margin-right: 0 !important;
  background: #ffffff;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

  .el-button {
    border-radius: 6px;
    font-weight: 500;

    &.el-button--primary {
      background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
      border: none;
      color: #ffffff;

      &:hover {
        background: linear-gradient(135deg, #3bc4b3 0%, #2aa3b8 100%);
        color: #ffffff;
      }
    }

    &.el-button--primary.is-plain {
      background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
      border: none;
      color: #ffffff;

      &:hover {
        background: linear-gradient(135deg, #3bc4b3 0%, #2aa3b8 100%);
        color: #ffffff;
      }
    }

    &.el-button--success.is-plain {
      background: linear-gradient(135deg, #67c23a 0%, #5daf34 100%);
      border: none;
      color: #ffffff;

      &:hover {
        background: linear-gradient(135deg, #5daf34 0%, #529b2e 100%);
        color: #ffffff;
      }
    }
  }
}

// 表格样式
:deep(.el-table) {
  border-radius: 8px;
  overflow: hidden;

  .el-table__header {
    th {
      background: #f8f9fa;
      color: #2c3e50;
      font-weight: 600;
      border-bottom: 2px solid #e4e7ed;
    }
  }

  .el-table__body {
    tr {
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        background: #f5f7fa;
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      }
    }
  }
}

// 标签样式
:deep(.el-tag) {
  border-radius: 4px;
  font-weight: 500;
  font-size: 12px;
}

// 对话框样式
:deep(.el-dialog) {
  border-radius: 12px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);

  .el-dialog__header {
    background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
    border-radius: 12px 12px 0 0;
    padding: 20px 24px;
    border-bottom: 1px solid #e4e7ed;

    .el-dialog__title {
      font-weight: 600;
      color: #2c3e50;
      font-size: 16px;
    }
  }

  .el-dialog__body {
    padding: 24px;
  }

  .el-dialog__footer {
    padding: 16px 24px;
    background: #f8f9fa;
    border-radius: 0 0 12px 12px;
    border-top: 1px solid #e4e7ed;

    .el-button {
      border-radius: 6px;
      font-weight: 500;
      padding: 8px 20px;

      &:not(.el-button--primary) {
        background: #ffffff;
        border: 1px solid #dcdfe6;
        color: #606266;

        &:hover {
          background: #f5f7fa;
          border-color: #c0c4cc;
          color: #606266;
        }
      }
    }
  }
}

// 描述列表样式
:deep(.el-descriptions) {
  .el-descriptions__header {
    margin-bottom: 16px;
  }

  .el-descriptions__title {
    font-size: 16px;
    font-weight: 600;
    color: #2c3e50;
  }

  .el-descriptions__body {
    .el-descriptions__table {
      .el-descriptions__cell {
        padding: 12px 16px;
        border-color: #e4e7ed;

        &.el-descriptions__label {
          background: #f8f9fa;
          font-weight: 600;
          color: #2c3e50;
        }

        &.el-descriptions__content {
          background: #ffffff;
          color: #606266;
        }
      }
    }
  }
}

// 分页样式
:deep(.el-pagination) {
  margin-top: 20px;
  text-align: center;

  .el-pagination__total {
    color: #606266;
    font-weight: 500;
  }

  .btn-prev,
  .btn-next {
    border-radius: 6px;
    border: 1px solid #dcdfe6;
    background: #ffffff;
    color: #606266;

    &:hover {
      color: #4fdaca;
      border-color: #4fdaca;
    }
  }

  .el-pager li {
    border-radius: 6px;
    margin: 0 2px;
    border: 1px solid #dcdfe6;
    background: #ffffff;
    color: #606266;

    &:hover {
      color: #4fdaca;
      border-color: #4fdaca;
    }

    &.is-active {
      background: linear-gradient(135deg, #4fdaca 0%, #32b7cb 100%);
      border-color: #4fdaca;
      color: #ffffff;
    }
  }
}

// 日期选择器样式
:deep(.el-date-editor) {
  .el-input__wrapper {
    border-radius: 6px;
    transition: all 0.3s ease;

    &:focus-within {
      box-shadow: 0 0 0 2px rgba(79, 218, 202, 0.2);
    }
  }

  .el-input__inner {
    border-radius: 6px;
    transition: all 0.3s ease;
  }
}

// 选择器样式
:deep(.el-select) {
  .el-input__wrapper {
    border-radius: 6px;
    transition: all 0.3s ease;

    &:focus-within {
      box-shadow: 0 0 0 2px rgba(79, 218, 202, 0.2);
    }
  }

  .el-input__inner {
    border-radius: 6px;
    transition: all 0.3s ease;
  }
}

// 输入框样式
:deep(.el-input) {
  .el-input__wrapper {
    border-radius: 6px;
    transition: all 0.3s ease;

    &:focus-within {
      box-shadow: 0 0 0 2px rgba(79, 218, 202, 0.2);
    }
  }

  .el-input__inner {
    border-radius: 6px;
    transition: all 0.3s ease;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .app-container {
    padding: 10px;
  }

  .el-form {
    .el-form-item {
      margin-bottom: 16px;
    }
  }

  :deep(.el-dialog) {
    width: 95% !important;
    margin: 0 auto;
  }
}
</style>
